<?php
use Phalcon\Mvc\Controller;
use Phalcon\Mvc\View;
use Phalcon\Session;
use Phalcon\Http\Request;
class Apph5Controller extends ControllerBase
{

    public function initialize()
    {
        header("Access-Control-Allow-Origin:*");
        header('Access-Control-Allow-Methods:POST,GET');
        header('Access-Control-Allow-Headers:x-requested-with, content-type');
        header('Content-Type:application/json');
    }



    /**
     * 根据邀请码获取上级邀请人
     */
    public function comforimAction(){
        $params = $this->request->get();
        if(!isset($params['invite_code'])|| empty($params['invite_code'])){
            $this->h5fail(-1,'请输入邀请码');
        }
        $user = new Member();
        $invite_user = $user->find_by_inviteCode($params['invite_code']);
        if(empty($invite_user)){
            $this->h5fail(-1,'没有找到上级邀请人');
        }
        $data['id']=$invite_user['id'];
        $data['nickname']=$invite_user['nickname'];
        $data['avatar']=$invite_user['avatar'];
        $this->h5ok($data);
    }



    /**
     * @func 发送验证码
     * @return json
     */
    public function send_codeAction(){
        $request = new Request();
        if($request->isPost() != true) {
            return $this->h5fail(-1,'请求方式错误');
        }
        $params = $this->request->getPost();
        if(!isset($params['phone']) || empty($params['phone'])){
            $this->h5fail(-1,'手机号码不能为空');
        }else{
            if(!preg_match("/^1[3456789]{1}\d{9}$/",$params['phone'])){
                $this->h5fail(-1,'手机号码错误');
            }
        }
        $rand_code = rand(111111,999999);
        $code = new Codes();
        $find_phone = $code->find_by_phone($params['phone']);
        if(!isset($params['is_login']) || empty($params['is_login'])){
            $params['is_login'] = 1;
        }

        $user = new Member();
        $user_phone = $user->find_by_phone($params['phone']);
        if($user_phone){
            if($user_phone['is_disable']){
                $this->h5fail(-1,'违规账号已冻结');
            }
        }

        if($params['is_login'] == 1){           //注册
            if(!isset($params['source']) || empty($params['source'])){      //网页端注册没有传平台
                if($user_phone){
                    $this->h5fail(-1,'该手机号已经注册了巨折app');
                }
            }
            if($user_phone['wx_account']){
                $this->h5fail(-1,'该手机已经绑定了别的微信，请先解绑');
            }
            $template_type = 1;
            $title="注册验证";
        }elseif ($params['is_login'] == 2){     //登录
            if (isset($params['source']) || !empty($params['source'])) {         //app端根据平台来弹出不同的邀请码
                //if($params['source'] != 'ios') {                   //关闭ios的审核模式
                if(empty($user_phone)) {
                    $this->h5fail(2, '您还没有注册，请使用微信登录');
                }else{
                    if (empty($user_phone['wx_account'])) {
                        $this->h5fail(2, '您还没有绑定微信，请用微信登录');
                    }
                }
                //}
            }
            $template_type = 2;
            $title="登录验证";
        }elseif($params['is_login'] == 3){      //变更信息
            $template_type = 3;
            $title="变更验证";
        }else{
            $this->h5fail(-1,'is_login参数错误');
        }

        if(strtotime($find_phone['expire_at']) > time()){
            $this->h5fail(-1,'验证码发送太频繁，请稍后发送');
        }

        $data['id'] = $find_phone['id'];
        $data['created_at'] = $find_phone['created_at'];
        $data['updated_at'] = date('Y-m-d H:i:s',time());
        $data['recipient'] = $params['phone'];
        $data['code'] = $rand_code;
        $data['expire_at'] = date('Y-m-d H:i:s',time()+1*60);//5分钟有效
        $result_code = $code->save_codes($data);
        if($result_code){
            $sms_result = $this->sms->send($params['phone'],$title,$rand_code,$template_type);
            if($sms_result){
                $this->h5ok([]);
            }else{
                $this->h5fail(-1,'由于网络原因，短信发送失败，请稍后重试');
            }
        }else{
            $this->h5fail(-1,'验证码出错');
        }
    }



    /**
     * 验证短信验证码 H5拉新页面
     */
    public function validate_phone_codeAction(){
        $request = new Request();
        if($request->isPost() != true) {
            return $this->h5fail(-1,'请求方式错误');
        }
        $params = $this->request->getPost();
        //手机验证码登录
        if (!isset($params['phone']) || empty($params['phone'])) {
            $this->h5fail(-1, '手机号码不能为空');
        } else {
            if (!preg_match("/^1[3456789]{1}\d{9}$/", $params['phone'])) {
                $this->h5fail(-1, '手机号码错误');
            }
        }
        if (!isset($params['smscode']) || empty($params['smscode'])) {
            $this->h5fail(-1, '验证码不能为空');
        }
        $code_obj = new Codes();
        $find_code_phone = $code_obj->find_by_phone($params['phone']);
        if ($find_code_phone) {
            if (strtotime($find_code_phone['expire_at']) < time()) {
                $this->h5fail(-1, '验证码过期，请从新获取');
            }
            if ($find_code_phone['code'] != $params['smscode']) {
                $this->h5fail(-1, '验证码输入错误');
            }
        } else {
            $this->h5fail(-1, '请获取验证码');
        }
        $this->h5ok([]);
    }


    public function loginh5Action(){
        $params = array_merge($this->request->get(),$this->request->getPost());
        $invite_code = "{$params['phone']}_{$params['smscode']}_{$params['invite_code']}";
        $this->wx->geth5token($invite_code);
    }




    /**
     * @func 登录
     */
    public function loginAction(){
        $request = new Request();
        $user = new Member();
        if($request->isPost() != true) {
            return $this->h5fail(-1,'请求方式错误');
        }
        $params = $this->request->getPost();
        //手机验证码登录
        if (!isset($params['phone']) || empty($params['phone'])) {
            $this->h5fail(-1, '手机号码不能为空');
        } else {
            if (!preg_match("/^1[3456789]{1}\d{9}$/", $params['phone'])) {
                $this->h5fail(-1, '手机号码错误');
            }
        }

        /**
         * ios审核模式
         */
        if($params['source'] != 'ios' || $params['phone'] != '13460542136') {
            if (!isset($params['smscode']) || empty($params['smscode'])) {
                $this->h5fail(-1, '验证码不能为空');
            }
            $code_obj = new Codes();
            $find_code_phone = $code_obj->find_by_phone($params['phone']);
            if ($find_code_phone) {
                if (strtotime($find_code_phone['expire_at']) < time()) {
                    $this->h5fail(-1, '验证码过期，请从新获取');
                }
                if ($find_code_phone['code'] != $params['smscode']) {
                    $this->h5fail(-1, '验证码输入错误');
                }
            } else {
                $this->h5fail(-1, '请获取验证码');
            }
        }


        $data = $user->find_by_phone($params['phone']);
        if(empty($data)){
            $data['phone']=$params['phone'];
            $data['referer_id']=1005;
            $data['path']=0;
            $data['invite_code']='';
            $data['created_at'] = date('Y-m-d H:i:s');
            $child_flag = true;        //是否有下级用户 没有下级
        }else{
            if($data['is_disable'] == 1){
                $this->h5fail(-1, '该账号由于违规操作，已经被禁用');
            }
            $directuser = new Member();
            $datetime['start_end_time'] =[];
            $directFanscount = $directuser->getDirectFansCount($data['id'],$datetime);
            if($directFanscount){       //找到下级
                $child_flag = false;    //有下级
            }else{
                $child_flag = true;     //没有下级
            }

        }

        if(isset($params['invite_code']) && !empty($params['invite_code'])){            //用户填入邀请码
            if(empty($data['invite_code']) && $child_flag) {
                $invite_user = $user->find_by_inviteCode($params['invite_code']);
                if (empty($invite_user)) {
                    $this->h5fail(-1, '邀请码不存在');
                }
                if (empty($invite_user['invite_code']) || empty($invite_user['phone'])) {
                    $this->h5fail(-1, '该邀请码不是有效的会员');
                }
                $data['referer_id'] = $invite_user['id'];
                if ($invite_user['path'] == '') {
                    $data['path'] = $invite_user['referer_id'];
                } else {
                    $data['path'] = $invite_user['path'] . ',' . $invite_user['referer_id'];
                }
                $invitecode = new InviteCodes();
                $data['invite_code'] = $invitecode->usedInviteCode();       //创建邀请码
            }
        }



        if(isset($params['union_id']) && !empty($params['union_id'])){                  //用户传入了微信号码
            $wx_userobj = new Member();
            $wx_user_info = $wx_userobj->find_by_wxaccount($params['union_id']);
            if ($wx_user_info) {                                                       //微信存在的时候

                if(isset($data['wx_account']) && !empty($data['wx_account'])){     //判断当前登录的手机是否已经绑定了
                    $this->h5fail(-1,'该手机号已经绑定了微信');
                }

                if ($wx_user_info['phone']) {                                       //判断该微信的手机是否已经绑定
                    $this->h5fail(-1, '该微信已经绑定了手机账号');
                }

                if(empty($data['invite_code']) && $child_flag) {       //如果手机号码存在邀请码
                    $data['referer_id'] = $wx_user_info['referer_id'];
                    $data['path'] = $wx_user_info['path'];
                    $data['invite_code'] = $wx_user_info['invite_code'];
                }


                $write = '删掉的微信：' . json_encode($wx_user_info) . '写入的日期：' . date('Y-m-d H:i:s', time()) . "\n";
                $create_file = '../cache/reg_del_' . $wx_user_info['invite_code'] . '.log';       //创建文件
                file_put_contents($create_file, $write, FILE_APPEND | LOCK_EX);
                $wx_user = new Member();
                $dele_wxaccount = $wx_user->find_by_wxaccountobj($params['union_id']);
                $del_result = $dele_wxaccount->delete();
                if ($del_result) {
                    $wallets = new Wallets();
                    $wallets_user = $wallets->findbyUserId($wx_user_info['id']);
                    $wallets_user->delete();
                }
                $invitecode = new InviteCodes();
                $wxaccount_invitecode = $invitecode->findbyId($wx_user_info['invite_code']);
                if ($wxaccount_invitecode) {
                    if ($wxaccount_invitecode['used'] == 1) {
                        $wxaccount_invitecode['used'] = 0;
                        $invitecode->save_invite($wxaccount_invitecode);
                    }
                }
            }

            $data['wx_account'] = $params['union_id'];
            $data['wx_nickname'] = (isset($params['nickname']) && !empty($params['nickname'])) ? $params['nickname'] : '';
            $data['avatar'] = (isset($params['avatar']) && !empty($params['avatar'])) ? $params['avatar'] : '';
            $data['gender'] = (isset($params['gender']) && !empty($params['gender'])) ? $params['gender'] : '';
        }



        if((isset($params['invite_code']) && !empty($params['invite_code'])) && (isset($params['union_id']) && !empty($params['union_id']))) {                            //存在邀请码和存在微信

            if(empty($data['invite_code']) && $child_flag) {
                $invite_user = $user->find_by_inviteCode($params['invite_code']);
                if (empty($invite_user)) {
                    $this->h5fail(-1, '邀请码不存在');
                }
                if (empty($invite_user['invite_code']) || empty($invite_user['phone'])) {
                    $this->h5fail(-1, '该邀请码不是有效的会员');
                }
                if (empty($params['invite_code'])) {
                    $data['referer_id'] = $invite_user['id'];
                    if ($invite_user['path'] == '') {
                        $data['path'] = $invite_user['referer_id'];
                    } else {
                        $data['path'] = $invite_user['path'] . ',' . $invite_user['referer_id'];
                    }
                    $invitecode = new InviteCodes();
                    $data['invite_code'] = $invitecode->usedInviteCode();       //创建邀请码
                }
            }

            $data['wx_account'] = $params['union_id'];
            $data['wx_nickname'] = (isset($params['nickname']) && !empty($params['nickname'])) ? $params['nickname'] : '';
            $data['avatar'] = (isset($params['avatar']) && !empty($params['avatar'])) ? $params['avatar'] : '';
            $data['gender'] = (isset($params['gender']) && !empty($params['gender'])) ? $params['gender'] : '';
        }

        if(isset($params['is_appuser'])){           //记录app端注册还是h5注册 h5传入了，app没有传入
            $data['is_appuser']=0;
        }else{
            $data['is_appuser']=1;
        }

        $usernew = new Member();
        $result = $usernew->save_user($data);
        if($result){
//            if($data['invite_code'] == '') {
//                CommonController::invite($data['referer_id'], $data['path']);        //直邀，间邀，团队人数累加
//            }
//            $user_login_log = new UserLoginlog();
//            $user_login_log->loginlog_save($data['phone']);
            $user1 = new Member();
            $info = $user1->find_by_phone($data['phone']);
            if(empty($info['invite_code'])){
                $this->h5ok($info,1);
            }
            $this->h5ok($info);
        }else{
            $this->h5fail(-1,'用户创建失败，请重试');
        }

    }




    public function h5ok($data = null,$code=1,$msg='操作成功')
    {
        $return_data['code']=$code;
        $return_data['data']=$data;
        $return_data['msg']=$msg;
        echo json_encode($return_data,1);
        exit();
    }
    public function h5fail($code=0,$msg)
    {
        $return_data['code']=$code;
        $return_data['msg']=$msg;
        echo json_encode($return_data,1);
        exit();
    }


}
